package com.github.rpc4j.producer.zk;

import org.apache.log4j.Logger;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;

import com.github.rpc4j.producer.config.Rpc4jProducerConfig;
import com.github.rpc4j.producer.service.Service;
import com.github.rpc4j.util.JsonUtil;
import com.github.rpc4j.util.ServerUtil;
import com.netflix.curator.framework.CuratorFramework;
import com.netflix.curator.framework.CuratorFrameworkFactory;
import com.netflix.curator.retry.RetryNTimes;

public class ZkUtil {
	
	private final static Logger logger = Logger.getLogger(ZkUtil.class);
	
	private Rpc4jProducerConfig config;
	
	private static final String RPC4J_ROOT_PATH = "/rpc4j";
	
	private static final String RPC4J_SERVER_PATH = "servers";
	
	private static final String RPC4J_SERVICE_PATH = "services";
	
	private String zkServerPath = null;
	
	private CuratorFramework client = null;
	
	public ZkUtil(Rpc4jProducerConfig config){
		this.config = config;
	}
	
	
	public void init(){
        try{
        	client = CuratorFrameworkFactory.builder().connectString(config.getZkServer()).namespace(RPC4J_ROOT_PATH).retryPolicy(new RetryNTimes(Integer.MAX_VALUE, 1000))
			.connectionTimeoutMs(5000).build();
        	client.start();
        	
        	isNotExistCreate(RPC4J_SERVER_PATH,null,CreateMode.PERSISTENT);
        	isNotExistCreate(RPC4J_SERVICE_PATH,null,CreateMode.PERSISTENT);
        	
        	String server = ServerUtil.getServerIp()+":"+config.getRpcPort();
        	
        	zkServerPath = RPC4J_SERVER_PATH+"/"+server;
        	isNotExistCreate(zkServerPath,config.getId().getBytes(),CreateMode.PERSISTENT);
	     }catch(Exception e){
	    	logger.error(e);
		}finally{
			
		}
	}
	
	public void registerService(Service service){
		String info = JsonUtil.toJson(service);
		String zkServerServicePath = zkServerPath+"/"+service.getServiceInterface();
		String servicePath = RPC4J_SERVICE_PATH +"/"+service.getServiceInterface();
		try{
			isNotExistCreate(zkServerServicePath,info.getBytes(),CreateMode.EPHEMERAL);
			isNotExistCreate(servicePath,null,CreateMode.PERSISTENT);
			String server = ServerUtil.getServerIp()+":"+config.getRpcPort();
			servicePath = servicePath+ "/"+ server;
			isNotExistCreate(servicePath,info.getBytes(),CreateMode.EPHEMERAL);
		
		}catch(Exception e){
			e.printStackTrace();
	    	logger.error(e);
		}finally{
			
		}
	}
	
	public void isNotExistCreate(String path,byte[] data,CreateMode mode){
		try{
		    Stat stat = client.checkExists().forPath(path);
		    if(stat==null){
		    	client.create().withMode(mode).forPath(path,data);
		    }
		}catch(Exception e){
	    	logger.error(e);
		}finally{
			
		}
	}
	
	
	
	
	

}
